<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import ThreeHelper from './ThreeHelper'
import cityGLB from './model/city.glb?url'
import { Color, Mesh, MeshStandardMaterial } from 'three'
import modifyCityMaterial from './util/modifyCityMaterial'

const contentRef = ref<HTMLElement>()
let threeHelper: ThreeHelper

const init = async (helper: ThreeHelper) => {
  helper.addAxesHelper()
  helper.addStats()
  helper.addOrbitControls()
  helper.addCommonLights()
  helper.camera.position.set(3, 10, 20)
  helper.frameRender()

  const cityModel = await helper.loadGLTF(cityGLB)
  const cityMaterial = new MeshStandardMaterial({ color: new Color('#051631') })
  cityModel.scene.traverse((item) => {
    if (item instanceof Mesh) {
      item.material = cityMaterial
      modifyCityMaterial(item)
      if (item.name === 'Layerbuildings') {
        const edgeMesh = helper.generateEdges({ geometry: item.geometry })
        const size = item.scale.x
        edgeMesh.scale.set(size, size, size)
        helper.add(edgeMesh)
      }
    }
  })
  helper.add(cityModel.scene)
}

onMounted(() => {
  threeHelper = new ThreeHelper({ targetDom: contentRef.value! })
  init(threeHelper)
})

onUnmounted(() => {
  threeHelper.destroy()
})
</script>

<template>
  <div class="city-page" ref="contentRef"></div>
</template>

<style lang="scss" scoped>
.city-page {
  width: 100%;
  height: 100%;
}
</style>
